<template>
  <Layout>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form">
        <!--    <Col span="8">
                <FormItem label="企业名称：" prop="esName">
                    <Input class="query-form-el"  type="text" v-model="form1.stdOrgName" ></Input>
                </FormItem>
            </Col>-->
        <Col span="8">
          <FormItem label="企业名称：">
            <!--                  <cascader-dom class="query-form-el" ref='queryOrgCascader'-->
            <!--                                @setOrgname='(orgName)=>{form1.stdOrgName = orgName}' :orgTree="true"-->
            <!--                                :setCurrentName="{label:form1.stdOrgName,value:form1.companyId}"></cascader-dom>-->
            <company-select v-model="form1.orgName" class="query-form-el"></company-select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="评定状态：" prop="esTypeId">
            <Select class="query-form-el" filterable v-model="form1.appStatusId">
              <Option v-for="item in appStatusList" :value="item.codingCodeId" :key="item.codingCodeId">{{
                  item.codingName
                }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8" v-if="!switchFlag">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开
            <Icon type="ios-arrow-down"/>
          </Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
        <Col span="8" v-else>
          <FormItem label="所在地：" prop="locationId">
            <Cascader :data="tempAreaTree" v-model="form1.locationId" change-on-select :transfer="true"
                      :load-data="areaTreeLoadData"
                      @on-change="(value,selectedData)=>{$set(form1,'locationId',value.join(','))}"></Cascader>
          </FormItem>
        </Col>

      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="初次通过时间:">
            <Date-picker class="query-form-el" type="daterange" v-model="appDate"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="达标等级:">
            <Select filterable v-model="form1.stdRankId" class="query-form-el">
              <Option v-for="item in stdRankList" :value="item.codingCodeId"
                      :key="item.codingCodeId">{{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="有效期:">
            <Select filterable v-model="form1.timeValidity">
              <Option value="1">请延续</Option>
              <Option value="2">已过期</Option>
              <Option value="3">未到期</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8">
          <FormItem label="二级集团公司:">
            <Select class="query-form-el" v-model="form1.twoCompanyId" filterable>
              <Option v-for="item in twoLevelOrgList" :value="item.orgId" :key="item.orgId">{{
                  item.orgName
                }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="16">
          <Div style="float: right;">
            <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起
              <Icon type="ios-arrow-up"/>
            </Button>
            <Button @click="reset" class="ivu-btn-reset">重置</Button>
            <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
          </Div>
        </Col>
      </Row>
      <Row class="query-form">
        <Col span="24">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo">新增</Button>
          <!--          <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="exportExcel">导出</Button>-->
          <download-button :api="exportUrl" :query-form="form1" :export-form-before="exportExcel"/>
        </Col>
      </Row>
    </Form>

    <Table ref='table' :height="tableHeight" size="small" :loading="loading" no-data-text="没有查询到相关数据!"
           @on-selection-change='getSelectRows' @on-sort-change="sortChange"
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize"
              @on-change="pageChange" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>
    <Modal :title="add?'安全标准化新增':'安全标准化修改'" :mask-closable="false" v-if="form1datacopy && model1" :transfer=false
           v-model="model1" :width=900>
      <Row>
        <Col span="24">
          <Form ref="form1datacopy" :model="form1datacopy" :rules="ruleCustom" label-position="top">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="企业名称：" prop="stdOrgId">
                  <cascaderDom class="query-form-el" style="padding-top: 4px" ref="trainOrg"
                               @setOrgInfo="setOrgId" @setOrgName="setOrgName"
                               :currentOrgId="stdOrgId"
                               :currentOrgName="stdOrgName" :orgTree="true"></cascaderDom>
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="所在地：" prop="locationId">
                  <!-- <Select filterable v-model="form1datacopy.locationId" @on-change="selectLocation"
                           :label-in-value="true">
                       <Option v-for="item in locationList" :value="item.codingCodeId"
                               :key="item.codingCodeId">{{ item.codingName }}
                       </Option>
                   </Select>-->
                  <Cascader class="query-form-el" :data="tempAreaTree" v-model="form1datacopy.locationArr"
                            change-on-select :transfer="true"
                            :load-data="areaTreeLoadData" :render-format="labels=>labels.join('·')" :clearable='false'
                            @on-change="(value,selectedData)=>{$set(form1datacopy,'locationId',value.join(','))}"></Cascader>
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="已通过安全标准化建设达标等级：" prop="stdRankId">
                  <Select filterable v-model="form1datacopy.stdRankId" @on-change="selectstdRank"
                          class="query-form-el"
                          :label-in-value="true">
                    <Option v-for="item in stdRankList" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="评定状态：" prop="appStatusId">
                  <Select filterable v-model="form1datacopy.appStatusId" @on-change="selectAppStatus"
                          class="query-form-el"
                          :label-in-value="true">
                    <Option v-for="item in appStatusList" :value="item.codingCodeId"
                            :key="item.codingCodeId">{{ item.codingName }}
                    </Option>
                  </Select>
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="初次通过时间:" prop="appDate">
                  <DatePicker :disabled="!add" type="date" placeholder="请选择" class="query-form-el"
                              v-model="form1datacopy.appDate"></DatePicker>
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="下次复评计划时间:" prop="dateAppDate">
                  <DatePicker type="date" placeholder="请选择" class="query-form-el"
                              v-model="form1datacopy.dateAppDate"></DatePicker>
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="7">
                <FormItem label="标准化组织评审单位：">
                  <Input type="text" class="query-form-el" v-model="form1datacopy.assessOrganizer"/>
                </FormItem>
              </Col>
              <Col span="7">
                <FormItem label="标准化评审单位：">
                  <Input type="text" class="query-form-el" v-model="form1datacopy.assessOrgName"/>
                </FormItem>
              </Col>
              <Col span="7" v-if="this.form1datacopy.reEvaluation=='1'">
                <!-- 最近一次评价时间： -->
                <FormItem label="复评通过时间：" prop="lastEvaluateTime">
                  <DatePicker type="date" placeholder="请选择" class="query-form-el"
                              v-model="form1datacopy.lastEvaluateTime"></DatePicker>
                </FormItem>
              </Col>
              <Col v-else span="7"></Col>
            </Row>

            <Row v-if="add" type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label=" 标准化通过附件（证书，牌匾等）：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file)=> beforeUpload(file,'')"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.filter(t=>!t.field).length>0" v-for="item in uploadList.filter(t=>!t.field)" :key='item'>
                    <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)" style="margin-left: 5px;margin-bottom: 3px" />
                  </div>
                </FormItem>
              </Col>
            </Row>
            <Row v-else type="flex" justify="space-around" class="code-row-bg">
              <Col v-if="this.form1datacopy.reEvaluation=='0'" span="23">
                <FormItem label=" 标准化通过附件（证书，牌匾等）：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file)=> beforeUpload(file,'')"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.filter(t=>!t.field).length>0" v-for="item in uploadList.filter(t=>!t.field)" :key='item'>
                    <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)" style="margin-left: 5px;margin-bottom: 3px" />
                  </div>
                </FormItem>
              </Col>

              <Col v-else span="23">
                <FormItem label="复评证书：">
                  <div>
                    <Upload ref="upload"
                            :before-upload="(file)=> beforeUpload(file,form1datacopy.type)"
                            :show-upload-list="true"
                            :max-size="10240"
                            multiple
                            type="drag"
                            :action="fileUrl">
                      <div style="padding: 10px">
                        <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                        <p>点击将文件拖拽到这里上传</p>
                        <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                      </div>
                    </Upload>
                  </div>
                  <div v-show="uploadList.filter(t=>t.field==form1datacopy.type).length>0" v-for="item in uploadList.filter(t=>t.field==form1datacopy.type)" :key='item'>
                    <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                    <Button type="text" icon="md-trash" @click="remove1(item.id)"
                            style="margin-left: 5px;margin-bottom: 3px"/>
                  </div>
                </FormItem>
              </Col>
            </Row>

            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="23">
                <FormItem label="备注（过期原因和工作进度）：" prop="notes">
                  <Input v-model="form1datacopy.notes" type="textarea" :rows="2"/>
                </FormItem>
              </Col>


            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button :disabled="saveMod" class='ivu-btn-save' :loading="buttonLoading"
                @click="submit('form1datacopy')">确定
        </Button>
        <Button class='ivu-btn-cancel' @click="handleCancel">取消</Button>
      </div>
    </Modal>
    <Modal title="安全标准化详情" :transfer=false v-model="model2" :width=800 class="modal-view-detail">
      <Row>
        <Col span="24">
          <Form :model="form1datacopy" :label-width="160">
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="企业名称：" prop="stdOrgName">
                  {{ form1datacopy.stdOrgName }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="所在地：" prop="location">
                  {{ areaCodeToAreaName(form1datacopy.locationId) }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="已通过安全标准化建设达标等级：" prop="stdRank">
                  {{ form1datacopy.stdRank }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="评定状态：" prop="appStatus">
                  {{ form1datacopy.appStatus }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">

              <Col span="11">
                <FormItem label="初次通过时间:" prop="appDate">
                  {{ formatDate(new Date(form1datacopy.appDate), 'yyyy-MM-dd') }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="下次复评计划时间:" prop="dateAppDate">
                  {{ formatDate(new Date(form1datacopy.dateAppDate), 'yyyy-MM-dd') }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="标准化组织评审单位：" prop="assessOrganizer">
                  {{ form1datacopy.assessOrganizer }}
                </FormItem>
              </Col>
              <Col span="11">
                <FormItem label="标准化评审单位：" prop="assessOrgName">
                  {{ form1datacopy.assessOrgName }}
                </FormItem>
              </Col>
            </Row>
            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="11">
                <FormItem label="创建人：" prop="userName">
                  {{ form1datacopy.userName }}
                </FormItem>
              </Col>
              <Col span="11">
                <!-- <FormItem label="最近一次评价时间：" prop="lastEvaluateTime">
                  {{
                    form1datacopy.lastEvaluateTime == null ? "" : formatDate(new Date(form1datacopy.lastEvaluateTime), 'yyyy-MM-dd')
                  }}
                </FormItem> -->
              </Col>
            </Row>

            <!-- <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label=" 标准化通过附件（证书，牌匾等）：">
                  <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                    <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                  </div>
                </FormItem>
              </Col>
            </Row> -->

            <Row type="flex" justify="space-around" class="code-row-bg">
              <Col span="23">
                <FormItem label="备注：" prop="notes ">
                  {{ form1datacopy.notes }}
                </FormItem>
              </Col>
            </Row>

            <Row>
              <Col span="23">
              <!-- <FormItem label="评审记录："></FormItem> -->
              <FormItem label="" label-width="30">
                <Table height="200" size="small" no-data-text="没有查询到相关数据!"
                      border :columns="columns2" :data="form1datacopy.items">
                      <template slot-scope="{ row }" slot="type">
                        <div v-for="item in uploadList.filter(t=>t.field===row.type)" :key='item'>
                          <a @click="downloadFile(form1datacopy.standardId,item)">{{ item.fileName }}</a>
                        </div>
                      </template>
                </Table>
              </FormItem>
            </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <div slot="footer">
        <Button class='ivu-btn-save' @click="model2=false">关闭</Button>
      </div>
    </Modal>

  </Layout>
</template>

<script>
import {Api} from '../../../api'
import {sessionStorage} from '../../../common/cacheUtils.js';
import {mapState} from 'vuex'
import pageCommonFunction from '@/components/pageCommonFunction.js'
import cascaderDom from '../../../components/cascader-dom.vue';
import DownloadButton from "@/components/download-button";

export default {
  components: {
    DownloadButton,
    cascaderDom
  },
  computed: {
    ...mapState('trhg', {
      areaMap: state => state.area.areaMap ? state.area.areaMap : [],
      areaTreeMap: state => state.area.areaTreeMap ? state.area.areaTreeMap : {},
    }),
  },
  data() {
    return {
      ...this.createCommonDataField(),
      companyId: sessionStorage('userId').getObject('userId').companyId,
      appDate: ["", ""],
      appStatusList: [],
      fileUrl: Api.interestedPartiesUserFile,
      locationList: [],
      stdRankList: [],
      downloadUrl: Api.downloadMongoFile,
      upUrl: Api.uploadMongoFile,
      switchFlag: false,
      saveMod: false,
      form1: {},
      uploadList: [],
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns2: [
      {
          title: '评审通过时间',
          maxWidth: 120,
          align: 'center',
          key: 'appDate',
          render: (h, params) => {
              return h('div', [
                  (this.formatDate(new Date(params.row.appDate), 'yyyy-MM-dd'))
              ]);
          }
        },
        { title: '评审证书', align: 'center', slot: 'type' }
      ],
      columns1: [
        {
          title: "序号",
          width: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          title: '企业名称',
          fixed: 'left',
          minWidth: 250,
          align: 'center',
          key: 'stdOrgName',
        },
        {
          title: '有效期',
          fixed: 'left',
          minWidth: 130,
          align: 'center',
          key: 'stdOrgName',
          render: (h, params) => {
            const row = params.row;
            const color = row.timeValidity == '请延续' ? 'warning' : row.timeValidity == '已过期' ? 'error' : 'primary';

            return h('Tag', {
              props: {
                type: 'dot',
                color: color
              }
            }, row.timeValidity);
          }
        },
        {
          title: '所在地',
          minWidth: 150,
          align: 'center',
          key: 'locationId',
          render: (h, params) => {
            return h('span', this.areaCodeToAreaName(params.row.locationId));
          }

        },
        {
          title: '已通过安全标准化建设达标等级',
          minWidth: 130,
          align: 'center',
          key: 'stdRank',
        },
        {
          title: '评定状态',
          minWidth: 100,
          align: 'center',
          key: 'appStatus',
        },
        {
          title: '最近一次评价时间',
          minWidth: 120,
          align: 'center',
          key: 'lastEvaluateTime',
          sortable: "custom",
          // render: this.renderViewDate(),
          render: (h, params) => {
              return h('div', [
                  (this.formatDate(new Date(params.row.lastEvaluateTime), 'yyyy'))
              ]);
          }
        },
        {
          title: '初次通过时间',
          minWidth: 120,
          align: 'center',
          key: 'appDate',
          sortable: "custom",
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.appDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          title: '下次复评计划时间',
          minWidth: 120,
          align: 'center',
          key: 'dateAppDate',
          sortable: "custom",
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.dateAppDate), 'yyyy-MM-dd'))
            ]);
          }
        },
        {
          title: '创建人',
          minWidth: 100,
          align: 'center',
          key: 'userName',
        },
        {
          title: '标准化组织评审单位',
          minWidth: 150,
          align: 'center',
          key: 'assessOrganizer',
        },
        {
          title: '标准化评审单位',
          minWidth: 150,
          align: 'center',
          key: 'assessOrgName',
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 230,
          align: 'center',
          render: (h, params) => {
            if (this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUsrId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                || sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined) {
              return h('div', [
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                  },
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.showData(params, 2, "0");
                    }
                  }
                }, '修改'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',

                  },
                  on: {
                    click: () => {
                      this.showData(params, 3, "1");
                    }
                  }
                }, '复评'),
                h('Divider', {
                  props: {
                    type: 'vertical',
                  }
                }, ''),
                h('A', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    fontSize: '14px',
                    color: 'red'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: '<p>是否要删除？</p>',
                        onOk: () => {
                          this.deleteData(params);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除')
              ]);
            } else {
              return h('div', [
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px',},
                  on: {
                    click: () => {
                      this.showData(params, 1);
                    }
                  }
                }, '详情'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '修改'),
                h('Divider', {props: {type: 'vertical'}}, ''),
                h('A', {
                  props: {type: 'primary', size: 'small'},
                  style: {fontSize: '14px', color: '#c5c8ce'}
                }, '删除')
              ]);
            }

          }
        },

      ],
      ruleCustom: {
        stdOrgId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        locationId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        stdRankId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        appStatusId: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        cover: [
          {required: true, message: '  ', trigger: 'change'}
        ],
        assessOrganizer: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        assessOrgName: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        lastEvaluateTime: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        appDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        dateAppDate: [{
          validator: (rule, value, callback) => {
            if (value == null || value == '' || value == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],

      },
      stdOrgName: '',
      stdOrgId: '',
      add: false,
      model1: false,
      buttonLoading: false,
      model2: false,
      showdata: {},
      exportUrl: Api.exportSaStdStandard,
      location: null,
      form1datacopy: {},
      files: [],
      tableHeight: 10,
      loading: false,
      twoLevelOrgList: []
    }
  },
  async mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.selectCodingSort();
    let orgId = sessionStorage('userId').getObject('userId');
    this.pageStatus.baseLoading = true;
    await this.$store.dispatch('trhg/area/query', {scope: this}, {root: true});
    this.pageStatus.baseLoading = false
    /*    this.companyId = sessionStorage('userId').getObject('userId').companyId;*/
    this.query();
    this.tempAreaTree = this.areaTreeMap['0']
  },
  methods: {
    ...pageCommonFunction,
    sortChange(data) {
      if (data.order === 'asc' || data.order === 'desc') {
        let order = data.key
        this.form1.dynamicSort = order + ' ' + data.order
        this.query()
      }
    },
    getFiles() {
      let url = this.fileUrl + '/' + this.form1datacopy.standardId + '/files/saStdStandard'
      this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data
        }
      })
    },
    beforeUpload(file,type) {
      if (type) {
        type = '/' + type
      } else {
        type = ''
      }
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.form1datacopy.standardId + '/files/saStdStandard' + type
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功")
          this.getFiles();
        }
      })
      return false
    },
    downloadFile(guideId, file) {
      let url = this.fileUrl + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {

        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = file.fileName //标题
        aLink.click()
        document.body.appendChild(aLink)
      })
    },

    remove1(id) {
      console.log(id)
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles()
      })
    },

    selectLocation(location) {
      this.form1datacopy.locationId = location.value;
      this.form1datacopy.location = location.label;
    },
    selectstdRank(stdRank) {
      this.form1datacopy.stdRankId = stdRank.value;
      this.form1datacopy.stdRank = stdRank.label;
    },
    selectAppStatus(appStatus) {
      this.form1datacopy.appStatusId = appStatus.value;
      this.form1datacopy.appStatus = appStatus.label;
    },
    beforeUploadOther(file) {
      this.files.push(file);
      return false;
    },
    deleteFile(index) {
      this.files.splice(index, 1);
    },
    setOrgId(data) {
      this.form1datacopy.stdOrgId = data[data.length - 1];
    },
    setOrgName(data) {
      this.form1datacopy.stdOrgName = data;
    },
    deleteData(params) {
      let url = Api.deleteSaStdStandard;
      this.$http.delete(url + '/' + params.row.standardId, {params: {}}).then((res) => {
        if (res.data.status === 200) {
          this.$Message.success('成功');
          this.query()
        } else if (res.data.status === 201) {
          this.$Message.error(res.data.msg);

        }
      }).catch(e => {
        this.$Message.error('请求失败' + e);
      })
    },


    getSelectRows(rows) {
      this.deleteRows = rows;
    },
    batDelete() {

    },
    get_uuid() {
      let s = [];
      let hexDigits = "0123456789abcdef";
      for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4";
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
      s[8] = s[13] = s[18] = s[23] = "-";

      let uuid = s.join("");
      let reg = new RegExp("-", "g");
      let a = uuid.replace(reg, "");
      console.log(a);
      return a;
    },
    setOrgId1(data) {
      this.form1.orgId = data[data.length - 1];
    },
    setOrgName1(data) {
      this.form1.orgName = data;
    },
    addInfo() {
      this.uploadList = []
      this.saveMod = false;
      this.form1datacopy = {
        standardId: this.get_uuid(),
        reEvaluation: '0'
      };
      this.stdOrgName = '';
      this.stdOrgId = '';
      this.files = [];
      this.model1 = true;
      this.add = true;
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    handleCancel() {
      this.form1datacopy = {};
      this.model1 = false;
    },
    selectCodingSort() {
      this.$http.get(Api.queryCodeDetailBySortId + '/AS-000001', {params: {}}).then((res) => {
        this.appStatusList = res.data.data;
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/REGION-000001', {params: {}}).then((res) => {
        this.locationList = res.data.data;
      });
      this.$http.get(Api.queryCodeDetailBySortId + '/SSL-000001', {params: {}}).then((res) => {
        this.stdRankList = res.data.data;
      });
      this.$http.get(Api.twoPlusFourReceipt + '/twoLevelOrg').then((res) => {
        if (res.data.status == 200) {
          this.twoLevelOrgList = res.data.data;
        }
      });

    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 88;
      } else {
        this.tableHeight = this.tableHeight - 88;
      }
    },
    reset() {
      this.form1 = {};
      this.appDate = ["", ""];
      if (this.$refs.queryOrgCascader) {
        this.$refs.queryOrgCascader.resetCurrentOrg();
      }
      this.query();

    },
    exportExcel(data) {
      data.orgId = sessionStorage('userId').getObject('userId').companyId
      data.orgName = sessionStorage('userId').getObject('userId').companyName
      if (this.appDate[0] != "" && this.appDate[1] != "") {
        data.startDate = this.formatDate(new Date(this.appDate[0]), 'yyyy-MM-dd');
        data.endDate = this.formatDate(new Date(this.appDate[1]), 'yyyy-MM-dd');
      }

    },
    query() {
      this.loading = true;
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        orgId: sessionStorage('userId').getObject('userId').companyId,
        orgName: sessionStorage('userId').getObject('userId').companyName

      };
      if (this.appDate[0] != "" && this.appDate[1] != "") {
        this.form1.startDate = this.formatDate(new Date(this.appDate[0]), 'yyyy-MM-dd');
        this.form1.endDate = this.formatDate(new Date(this.appDate[1]), 'yyyy-MM-dd');
      }
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));

      let url = Api.querySaStdStandard;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    beforeEditDialogOpen(data) {
      if (data.row.locationId) {
        data.row.locationArr = data.row.locationId.split(',')
        data.row.companyAddressName = this.areaCodeToAreaName(data.row.locationId)
      }
    },
    async afterDataToViewInit(data) {
      if (data && data.locationId) {
        let companyAddressArr = data.locationId.split(',')
        this.tempAreaTree = []
        setTimeout(() => {
          this.tempAreaTree = this.addressEditArr(this.areaTreeMap, companyAddressArr)
        }, 100)
      }
    },
    showData(data, flag, reEvaluation) {

      this.stdOrgId = data.row.stdOrgId;
      this.stdOrgName = data.row.stdOrgName;
      if (flag == 1) {
        //查看页面
        this.beforeEditDialogOpen(data);
        this.form1datacopy = data.row;
        /*  this.form1datacopy.locationId = this.form1datacopy.locationId.split(',');*/
        this.form1datacopy.appDate = this.formatDate(new Date(this.form1datacopy.appDate), 'yyyy-MM-dd');
        this.form1datacopy.dateAppDate = this.formatDate(new Date(this.form1datacopy.dateAppDate), 'yyyy-MM-dd');
        this.getFiles()

        this.model2 = true;
      } else {
        this.saveMod = false;
        // this.form1datacopy.purchaseDate = this.formatDate(new Date(this.showdata.purchaseDate), 'yyyy-MM-dd');
        //修改页面
        this.add = false;
        this.files = [];
        this.beforeEditDialogOpen(data);
        this.form1datacopy = JSON.parse(JSON.stringify(data.row));
        this.form1datacopy.reEvaluation = reEvaluation
        /*  this.form1datacopy.locationId = this.form1datacopy.locationId.split(',');*/
        this.form1datacopy.appDate = this.formatDate(new Date(this.form1datacopy.appDate), 'yyyy-MM-dd');
        this.form1datacopy.dateAppDate = this.formatDate(new Date(this.form1datacopy.dateAppDate), 'yyyy-MM-dd');
        this.getFiles()
        this.model1 = true;
        this.afterDataToViewInit(this.form1datacopy)

      }
    },
    /*  submit(name) {
          this.$refs[name].validate((valid) => {
              if (valid) {
                  this.saveMod=true;
                  this.form1datacopy.appDate = this.formatDate(new Date(this.form1datacopy.appDate), 'yyyy-MM-dd');
                  this.form1datacopy.dateAppDate = this.formatDate(new Date(this.form1datacopy.dateAppDate), 'yyyy-MM-dd');
                  if (this.files.length>0) {
                      if(this.add){
                          let userId = sessionStorage('userId').getObject('userId').userId;
                          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                          this.form1datacopy.createUsrId = userId;
                          this.form1datacopy.createOrgId = orgId;
                          this.$http.post(Api.saveSaStdStandard, this.form1datacopy).then((res) => {
                              if (res.data.status === 200) {
                                  let ids = res.data.data;
                                  let formData = new FormData();
                                  for(let i =0;i < this.files.length;i ++){
                                      formData.append("files", this.files[i]);
                                  }
                                  //多附件上传
                                  this.$http.post(Api.interestedPartiesUserFile + '/' + ids + '/files/file', formData).then((res) => {
                                      if (res.data.result == "success") {
                                          this.$Message.success("保存成功");
                                          this.model1 = false;
                                          this.saveMod = false;
                                          this.query();
                                      } else {
                                          this.$Message.error("附件上传失败");
                                      }
                                  }).catch(e => {
                                      console.log(e);
                                      this.$Message.error("数据获取失败");
                                  })
                              }else if (res.data.status === 201) {
                                  this.$Message.error(res.data.msg);
                                  this.model1 = false;
                              }

                          }).catch(e => {
                              this.model1 = false;
                              this.query();
                              this.$Message.error("数据获取失败")
                          })
                      }else{
                          let userId = sessionStorage('userId').getObject('userId').userId;
                          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                          this.form1datacopy.updateUserId = userId;
                          this.form1datacopy.updateOrgId = orgId;
                          this.$http.post(Api.updateSaStdStandard, this.form1datacopy).then((res) => {
                              if (res.data.status === 200) {
                                  let ids = res.data.data;
                                  let formData = new FormData();
                                  for(let i =0;i < this.files.length;i ++){
                                      formData.append("files", this.files[i]);
                                  }
                                  //多附件上传
                                  this.$http.post(Api.uploadPTWFiles + '/' + ids + '/files/file', formData).then((res) => {
                                      if (res.data.result == "success") {
                                          this.$Message.success("保存成功");
                                          this.model1 = false;
                                          this.saveMod = false;
                                          this.query();
                                      } else {
                                          this.$Message.error("附件上传失败");
                                      }
                                  }).catch(e => {
                                      console.log(e);
                                      this.$Message.error("数据获取失败");
                                  })

                              }else if (res.data.status === 201) {
                                  this.$Message.error(res.data.msg);
                                  this.model1 = false;
                              }

                          }).catch(e => {
                              this.model1 = false;
                              this.query();
                              this.$Message.error("数据获取失败")
                          })
                      }

                  }else{
                      if(this.add){
                          let userId = sessionStorage('userId').getObject('userId').userId;
                          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                          this.form1datacopy.createUsrId = userId;
                          this.form1datacopy.createOrgId = orgId;
                          this.$http.post(Api.saveSaStdStandard, this.form1datacopy).then((res) => {
                              if (res.data.status === 200) {
                                  this.$Message.success('成功');
                                  this.model1 = false;
                                  this.saveMod = false;

                                  this.query()

                              }else if (res.data.status === 201) {
                                  this.$Message.error(res.data.msg);
                                  this.model1 = false;
                              }

                          }).catch(e => {
                              this.model1 = false;
                              this.query();
                              this.$Message.error("数据获取失败")
                          })
                      }else{
                          let userId = sessionStorage('userId').getObject('userId').userId;
                          let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
                          this.form1datacopy.updateUserId = userId;
                          this.form1datacopy.updateOrgId = orgId;
                          this.$http.post(Api.updateSaStdStandard, this.form1datacopy).then((res) => {
                              if (res.data.status === 200) {
                                  this.$Message.success('成功');
                                  this.saveMod = false;
                                  this.model1 = false;

                                  this.query()

                              }else if (res.data.status === 201) {
                                  this.$Message.error(res.data.msg);
                                  this.model1 = false;
                              }

                          }).catch(e => {
                              this.model1 = false;
                              this.query();
                              this.$Message.error("数据获取失败")
                          })
                      }
                  }

              } else {
                  this.$Message.error('请填报完整!');
              }
          })
      },*/
    submit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.buttonLoading = true
          this.saveMod = true;
          this.form1datacopy.appDate = this.formatDate(new Date(this.form1datacopy.appDate), 'yyyy-MM-dd');
          this.form1datacopy.dateAppDate = this.formatDate(new Date(this.form1datacopy.dateAppDate), 'yyyy-MM-dd');
          if (this.form1datacopy.lastEvaluateTime)
            this.form1datacopy.lastEvaluateTime = this.formatDate(new Date(this.form1datacopy.lastEvaluateTime), 'yyyy-MM-dd');
          else
            this.form1datacopy.lastEvaluateTime = null;
          if (this.add) {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.createUsrId = userId;
            this.form1datacopy.createOrgId = orgId;
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.saveSaStdStandard, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.model1 = false;
                this.saveMod = false;

                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("数据获取失败")
            })
          } else {
            let userId = sessionStorage('userId').getObject('userId').userId;
            let orgId = sessionStorage('userId').getObject('userId').orgInfo.orgId;
            this.form1datacopy.updateUserId = userId;
            this.form1datacopy.updateOrgId = orgId;
            this.$http.post(Api.updateSaStdStandard, this.form1datacopy).then((res) => {
              if (res.data.status === 200) {
                this.$Message.success('成功');
                this.saveMod = false;
                this.model1 = false;

                this.query()

              } else if (res.data.status === 201) {
                this.$Message.error(res.data.msg);
                this.model1 = false;
              }
              this.buttonLoading = false
            }).catch(e => {
              this.model1 = false;
              this.query();
              this.buttonLoading = false
              this.$Message.error("数据获取失败")
            })
          }


        } else {
          this.$Message.error('请填报完整!');
        }
      })
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },

  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {
        setTimeout(() => {
          this.$refs.trainOrg.setCurrentOrg();

        }, 100)
      } else {
        this.$refs.trainOrg.setCurrentOrg();

      }
    },

  },


}
</script>

<style lang='css' scoped>
@import '../../../index.css';
</style>
